<template>
    <a-card style="margin-bottom: 15px" size="small">
        <template #title>
            <div style="margin: 10px 0px 20px 0px;font-size:16px;">项目年度预算申请</div>
        </template>
        <template #extra>
            <a-tooltip title="返回上级">
                <a-button size="middle" @click="goback">
                    <template #icon>
                        <RollbackOutlined />
                    </template>
                </a-button>
            </a-tooltip>
        </template>
        <a-steps :current="current" :items="items" type="navigation" @change="StepsChange"></a-steps>
        <div class="steps-content">
            <a-form ref="formRef" :model="formData" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol"
                :labelWrap="true">
                <div v-show="steps[current].title == '项目以及预算年度'">
                    <a-form-item label="项目编号" name="blprojectnum">
                        <a-select v-model:value="formData.blprojectnum" :allowClear="true" size="Middle"
                            style="width: 100%" @change="onChangePro" :options="options" placeholder="请选择项目"></a-select>
                    </a-form-item>
                    <a-form-item label="项目名称" name="blapplyprojectname">
                        <a-input :disabled="true" style="width: 100%" v-model:value="formData.blapplyprojectname"
                            placeholder="项目名称">
                        </a-input>
                    </a-form-item>
                    <a-form-item label="预算年度" name="blyear">
                        <a-date-picker :valueFormat="'YYYY'" style="width: 100%" :allowClear="false"
                            :defaultValue="null" v-model:value="formData.blyear" picker="year" placeholder="请选择年份" />
                    </a-form-item>
                </div>
                <div v-show="steps[current].title == '人员支出'">
                    <div v-for="(item, index) in peoplePay" :key="index">
                        <a-form-item :label="item.bldataname" :name="`RYZC${index}bltotle`">
                            <a-input-number :step="0.01"
                                :parser="value =>value.match(/^[0-9]*\.([0-9]{0,2})|^[0-9]*/)[0]" string-mode
                                style="width: 100%" v-model:value.trim="item.bltotle" addon-after="元"
                                :placeholder="`请输入${item.bldataname}，例：10.00`"></a-input-number>
                        </a-form-item>
                        <a-form-item :label="`${item.bldataname}说明`" :name="`RYZC${index}bldetail`">
                            <a-textarea v-model:value.trim="item.bldetail" :rows="2"
                                :placeholder="`应注明${item.bldataname}具体的数量和金额`" />
                        </a-form-item>
                    </div>
                </div>
                <div v-show="steps[current].title == '公用支出'">
                    <div v-for="(item, index) in publicPay" :key="index">
                        <a-form-item :label="item.bldataname" :name="`GYZC${index}bltotle`">
                            <a-input-number :step="0.01"
                                :parser="value =>value.match(/^[0-9]*\.([0-9]{0,2})|^[0-9]*/)[0]" string-mode
                                style="width: 100%" v-model:value.trim="item.bltotle" addon-after="元"
                                :placeholder="`请输入${item.bldataname}，例：10.00`"></a-input-number>
                        </a-form-item>
                        <a-form-item :label="`${item.bldataname}说明`" :name="`GYZC${index}bldetail`">
                            <a-textarea v-model:value.trim="item.bldetail" :rows="2"
                                :placeholder="`应注明${item.bldataname}具体的数量和金额`" />
                        </a-form-item>
                    </div>
                </div>
                <div v-show="steps[current].title == '基建支出'">
                    <div v-for="(item, index) in buildPay" :key="index">
                        <a-form-item :label="item.bldataname" :name="`JJZC${index}bltotle`">
                            <a-input-number :step="0.01"
                                :parser="value =>value.match(/^[0-9]*\.([0-9]{0,2})|^[0-9]*/)[0]" string-mode
                                style="width: 100%" v-model:value.trim="item.bltotle" addon-after="元"
                                :placeholder="`请输入${item.bldataname}，例：10.00`"></a-input-number>
                        </a-form-item>
                        <a-form-item :label="`${item.bldataname}说明`" :name="`JJZC${index}bldetail`">
                            <a-textarea v-model:value.trim="item.bldetail" :rows="2"
                                :placeholder="`应注明${item.bldataname}具体的数量和金额`" />
                        </a-form-item>
                    </div>
                </div>
                <div v-show="steps[current].title == '其他资本性支出'">
                    <div v-for="(item, index) in otherPay" :key="index">
                        <a-form-item :label="item.bldataname" :name="`QTZBXZC${index}bltotle`">
                            <a-input-number :step="0.01"
                                :parser="value =>value.match(/^[0-9]*\.([0-9]{0,2})|^[0-9]*/)[0]" string-mode
                                style="width: 100%" v-model:value.trim="item.bltotle" addon-after="元"
                                :placeholder="`请输入${item.bldataname}，例：10.00`"></a-input-number>
                        </a-form-item>
                        <a-form-item :label="`${item.bldataname}说明`" :name="`QTZBXZC${index}bldetail`">
                            <a-textarea v-model:value.trim="item.bldetail" :rows="2"
                                :placeholder="`应注明${item.bldataname}具体的数量和金额`" />
                        </a-form-item>
                    </div>
                </div>
            </a-form>
        </div>
        <div class="steps-action">
            <a-space>
                <a-button v-if="current > 0" style="margin-left: 8px" @click="prev">
                    <ArrowLeftOutlined />上一步
                </a-button>
                <a-button v-if="current == steps.length - 1" v-throttle type="primary" @click="onSubmit"> 提交 </a-button>
                <a-button v-if="current < steps.length - 1" type="primary" @click="next">下一步
                    <ArrowRightOutlined />
                </a-button>
            </a-space>
        </div>
    </a-card>

</template>

<script setup>
    import { nextTick, reactive, ref, defineProps, onMounted, toRefs, toRaw } from 'vue';
    import { message, Modal } from 'ant-design-vue';
    import { smartSentry } from '/@/lib/smart-sentry';
    import { ProManageApi } from '/@/api/ProManage/ProManage-api';
    import { SmartLoading } from '/@/components/framework/smart-loading';
    const emits = defineEmits(['emitPass'])
    const goback = () => {
        let obj = {
            type: 0,
        };
        emits('emitPass', obj);
    };
    //  步骤条
    const current = ref(0);
    //点击步骤条的事件
    function StepsChange(e) {
        current.value = e;
    }
    //前进
    const next = () => {
        current.value++;
    };
    //后退
    const prev = () => {
        current.value--;
    };
    //步骤条标题
    const steps = [
        {
            title: '项目以及预算年度',
        },
        {
            title: '人员支出',
        },
        {
            title: '公用支出',
        },
        {
            title: '基建支出',
        },
        {
            title: '其他资本性支出',
        },
    ];
    const items = steps.map((item) => ({
        key: item.title,
        title: item.title,
    }));
    //表单验证规则
    const formRef = ref();
    const labelCol = {
        span: 5,
    };
    const wrapperCol = {
        span: 15,
    };
    const formData = reactive({});
    const rules = {
        blprojectnum: [
            {
                required: true,
                message: '请选择项目',
                trigger: 'change',
            },
        ],
        blyear: [
            {
                required: true,
                message: '请选择年份',
                trigger: 'change',
            },
        ],
    }
    // 所属项目
    const options = ref([])
    // 所属项目  onChangePro
    const onChangePro = (value, v) => {
        formData.blprojectnum = value
        let result = allProject.value.find(obj => obj.blprojectnum === value);
        formData.blapplyprojectname = result.blapplyprojectname
    }
    // 预算提交
    function onSubmit() {
        formRef.value
            .validate()
            .then(async () => {
                SmartLoading.show();
                try {
                    // 将数组合并为一个数组
                    const combinedData = [...peoplePay.value, ...publicPay.value, ...buildPay.value, ...otherPay.value];
                    // 提取只有 'bldatanum', 'bltotle', "bldetail" 属性的对象
                    function filterAndAddProperties(arr, props) {
                        const filteredArray = arr.filter(item => {
                            return props.every(prop => item.hasOwnProperty(prop));
                        });
                        const newArray = filteredArray.map(item => {
                            const newItem = {};
                            props.forEach(prop => {
                                newItem[prop] = item[prop];
                            });
                            return newItem;
                        });
                        return newArray;
                    }
                    const filteredAndAddedArray = filterAndAddProperties(combinedData, ['bldatanum', 'bldatafunum', 'bltotle', 'bldetail']);
                    const paramsObject = formData
                    paramsObject["blrecordVo"] = filteredAndAddedArray
                    // 
                    await ProManageApi.AddBudget(paramsObject);
                    message.success(`添加成功`);
                    let obj = {
                        type: 0,
                    };
                    emits('emitPass', obj)
                } catch (error) {
                    smartSentry.captureError(error);
                } finally {
                    SmartLoading.hide();
                }
            })
            .catch((error) => {
                message.error('参数验证错误，请仔细填写表单数据!');
                current.value = 0;
            });
    }
    const allProject = ref([])
    // 所有项目名称  
    async function getAllProjectList() {
        try {
            let departList = await ProManageApi.getFinishProject();
            allProject.value = departList.blapplyprojectinfo
            const dataSource = departList.blapplyprojectinfo
            options.value = dataSource.map(item => ({
                value: item.blprojectnum,
                // label: item.blapplyprojectname
                label: item.blprojectnum
            }));

        } catch (e) {
            smartSentry.captureError(e);
        } finally {

        }
    }
    // 新增待填项  AddlistData
    const peoplePay = ref([])//人员支出
    const publicPay = ref([])//公用支出
    const buildPay = ref([])//基建支出
    const otherPay = ref([])//其他资本性支出
    async function getAddData() {
        try {
            let departList = await ProManageApi.AddlistData();
            const dataSource = departList.data
            // 添加新的属性
            dataSource.forEach(item => {
                item.children.forEach(child => {
                    child.bldetail = '';
                    child.bltotle = '';
                });
            });
            peoplePay.value = dataSource.find(item => item.bldatanum === 'RYZC').children
            publicPay.value = dataSource.find(item => item.bldatanum === 'GYZC').children
            buildPay.value = dataSource.find(item => item.bldatanum === 'JJZC').children
            otherPay.value = dataSource.find(item => item.bldatanum === 'QTZBXZC').children
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
        }
    }
    onMounted(() => {
        getAllProjectList()
        getAddData()
    })
</script>

<style lang="less" scoped>
    .steps-content {
        width: 100%;
        border: 1px dashed #e9e9e9;
        border-radius: 6px;
        min-height: 510px;
        padding-top: 40px;
        margin: 20px auto;
    }

    .steps-action {
        margin-top: 24px;
        float: right;
    }
</style>